import addEvent from "./events";
import Subscribe from './subscribe';
import {
    debounce,
    isDebounceType
} from "./utils";

class Tutorial {
    constructor(config) {

        let defaultConfig = {
            ignoreWinEvent: [],
            ignoreDocEvent: [],
            ignoreEleEvent: [],
        };

        let _config = Object.assign(defaultConfig, config);

        this.prevEvent = null;
        this.subscribe = new Subscribe();
        this.init(_config);

        this.eventsMap = {};

    }

    init(config) {
        let winEvents = this.getAllEvents(window);
        let pickWinEvents = this.pickEvents(winEvents, config.ignoreWinEvent);
        // let docEvents = this.getAllEvents(document);
        // let eleEvents = this.getAllEvents(document.documentElement);
        // console.log('初始化', winEvents, docEvents, eleEvents);

        this.pickWinEvents = pickWinEvents;

        this.addAllEvents(pickWinEvents);

    }

    _watch = debounce(function (type, e) {
        this.publish(type, e);
    }, 400);

    watch = (e) => {
        e.stopPropagation();
        let type = e.type;;
        if (isDebounceType(type)) {
            this._watch(type, e);
            return;
        }

        this.publish(type, e);
    }

    publish(type, e) {
        this.subscribe.publish(type, {
            type: type,
            event: e,
            triggerTime: Date.now()
        });
        this.prevEvent = type;

    }

    addAllEvents(allEvents) {
        allEvents.forEach((events, index) => {
            let type = events.type;
            this.addEvent(window, type, this.watch)
        });
    }

    dispose() {
        this.pickWinEvents.forEach((events) => {
            let type = events.type;
            window.removeEventListener(type, this.watch);
        });
    }

    pickEvents(allEvents, ignoreEvents) {
        return allEvents.reduce(function (events, curEvent, index) {
            return ignoreEvents.indexOf(curEvent.type) > -1 ? events : (events[events.length] = curEvent, events);
        }, []);
    }

    getAllEvents(obj) {
        let events = [];
        for (let eventType in obj) {
            /^on/.test(eventType) && (events[events.length] = {
                originType: eventType,
                type: eventType.slice(2, )
            });
            // /^on/.test(eventType) && console.log('绑定的事件类型', eventType, eventType.slice(2, ));
        }
        return events;
    }

    addEvent(target, type, handler) {
        addEvent(target, type, handler)
    }

}

export default Tutorial;